#include "SocketIO.hpp"
#include <func.h>

namespace  ln{

int SocketIO::recvPeek(char * buf,int len) const{
    int ret = -1;

    do{
        ret = recv(_fd,buf,len,MSG_PEEK);
    }while(ret == -1 && errno == EINTR);

    return ret;
}

int SocketIO::recvn(char * buf,int len){
    char *pbuf = buf;
    int left = len;
    while(left > 0){
        int ret = recv(_fd,pbuf,left,0);
        if(ret == -1 && errno == EINTR){
            continue;
        }else if(ret == -1){
            perror("recv");
            return len - left;
        }else if(ret == 0){
            return len - left;
        }else{
            pbuf += ret;
            left -= ret;
        }
    }
    return len - left;
}
int SocketIO::readline(char * buf,int maxlen){
    char * pbuf = buf;
    int left = maxlen - 1;
    int total = 0; //记录读取的字节数
                   //
    while(left > 0){
        int ret = recvPeek(pbuf,left);

        //找到'\n'
        for(int i = 0;i < ret; ++i){
            if(pbuf[i] == '\n'){
                ret = recvn(pbuf,i + 1);
                total += ret;
                pbuf[i] = '\0';
                return total;
            }
        }

        //未找到'\n'
        recvn(pbuf,ret);
        pbuf += ret;
        left -= ret;
        total += ret;
    }

    //一直未查找到'\n'
    pbuf[maxlen - 1] = '\0';
    return maxlen - 1;
}
    
int SocketIO::sendn(const char * buf,int len){
    const char * pbuf = buf;
    int left = len;
    while(left > 0){
        int ret = send(_fd,pbuf,left,0);
        if(ret == -1 && errno == EINTR){
            continue;
        }else if(ret == -1){
            return len - left;
        }else{
            pbuf += ret;
            left -= ret;
        }
    }
    return len - left;
}

}//end of namespace ln

